<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 健康食谱管理系统</title>
    <link href="https://lib.baomitu.com/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://lib.baomitu.com/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        .sidebar {
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            z-index: 100;
            padding: 48px 0 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
            background-color: #f8f9fa;
            width: 250px;
        }
        .sidebar-sticky {
            position: relative;
            top: 0;
            height: calc(100vh - 48px);
            padding-top: .5rem;
            overflow-x: hidden;
            overflow-y: auto;
        }
        .navbar {
            box-shadow: 0 2px 4px rgba(0,0,0,.1);
        }
        main {
            margin-left: 250px;
            padding: 48px 15px 15px;
        }
        .table-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,.05);
            padding: 1.5rem;
            margin-top: 1rem;
        }
        .avatar-sm {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
        }
        .nav-link {
            color: #333;
            padding: 0.8rem 1rem;
        }
        .nav-link:hover {
            background-color: #e9ecef;
        }
        .nav-link.active {
            background-color: #007bff;
            color: white;
        }
        .nav-link i {
            width: 20px;
            text-align: center;
            margin-right: 10px;
        }
        .search-box {
            max-width: 300px;
        }
        .badge {
            font-size: 0.9em;
            padding: 0.4em 0.6em;
        }
        .table td {
            vertical-align: middle;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-dark bg-dark fixed-top">
        <div class="container-fluid">
            <span class="navbar-brand">健康食谱后台管理</span>
            <div class="d-flex">
                <span class="navbar-text me-3" id="adminName"></span>
                <button class="btn btn-outline-light btn-sm" onclick="handleLogout()">退出</button>
            </div>
        </div>
    </nav>

    <!-- 侧边栏 -->
    <nav class="sidebar">
        <div class="sidebar-sticky">
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link" href="index.html">
                        <i class="fas fa-home"></i>仪表盘
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="users.html">
                        <i class="fas fa-users"></i>用户管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="recipes.html">
                        <i class="fas fa-utensils"></i>食谱管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="foods.html">
                        <i class="fas fa-apple-alt"></i>食材管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="posts.html">
                        <i class="fas fa-comments"></i>帖子管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="sports.html">
                        <i class="fas fa-running"></i>运动记录
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="diets.html">
                        <i class="fas fa-hamburger"></i>饮食记录
                    </a>
                </li>
            </ul>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <main>
        <div class="container-fluid">
            <div class="d-flex justify-content-between align-items-center">
                <h1 class="h2">用户管理</h1>
                <div class="search-box">
                    <div class="input-group">
                        <input type="text" class="form-control" id="searchInput" placeholder="搜索用户...">
                        <button class="btn btn-outline-secondary" type="button" onclick="searchUsers()">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                </div>
            </div>

            <div class="table-container">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>头像</th>
                            <th>用户名</th>
                            <th>昵称</th>
                            <th>性别</th>
                            <th>身高(cm)</th>
                            <th>体重(kg)</th>
                            <th>年龄</th>
                            <th>BMI</th>
                            <th>健康目标</th>
                            <th>注册时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="userList">
                        <!-- 用户列表将通过JavaScript动态加载 -->
                    </tbody>
                </table>

                <nav aria-label="Page navigation" class="mt-4">
                    <ul class="pagination justify-content-center" id="pagination">
                        <!-- 分页将通过JavaScript动态加载 -->
                    </ul>
                </nav>
            </div>
        </div>
    </main>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    确定要删除该用户吗？此操作不可恢复。
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" onclick="confirmDelete()">确定删除</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://lib.baomitu.com/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentPage = 1;
        let deleteUserId = null;
        const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            console.log('页面加载完成');
            showAdminName();
            loadUsers();
        });

        // 显示管理员名称
        function showAdminName() {
            try {
                const adminUser = JSON.parse(localStorage.getItem('adminUser') || '{}');
                document.getElementById('adminName').textContent = adminUser.nickname || adminUser.username || '';
            } catch (error) {
                console.error('显示管理员名称失败:', error);
            }
        }

        // 处理退出登录
        function handleLogout() {
            localStorage.removeItem('adminToken');
            localStorage.removeItem('adminUser');
            window.location.href = '/admin/login.html';
        }

        // 计算BMI
        function calculateBMI(weight, height) {
            if (!weight || !height) return '-';
            const heightInMeters = height / 100;
            const bmi = weight / (heightInMeters * heightInMeters);
            return bmi.toFixed(1);
        }

        // 获取BMI状态
        function getBMIStatus(bmi) {
            if (bmi === '-') return '-';
            bmi = parseFloat(bmi);
            if (bmi < 18.5) return '偏瘦';
            if (bmi >= 18.5 && bmi < 24) return '正常';
            if (bmi >= 24 && bmi < 28) return '超重';
            return '肥胖';
        }

        // 获取BMI对应的badge类
        function getBMIBadgeClass(bmi) {
            if (bmi === '-') return 'bg-secondary';
            bmi = parseFloat(bmi);
            if (bmi < 18.5) return 'bg-warning';
            if (bmi >= 18.5 && bmi < 24) return 'bg-success';
            if (bmi >= 24 && bmi < 28) return 'bg-warning';
            return 'bg-danger';
        }

        // 加载用户列表
        async function loadUsers(page = 1, search = '') {
            try {
                console.log('开始加载用户数据');
                const token = localStorage.getItem('adminToken');
                console.log('Token:', token);

                if (!token) {
                    console.log('未找到token，跳转到登录页');
                    window.location.href = '/admin/login.html';
                    return;
                }

                // 显示加载提示
                document.getElementById('userList').innerHTML = '<tr><td colspan="12" class="text-center">加载中...</td></tr>';

                const response = await fetch(`/api/admin/users?page=${page}&limit=10&search=${search}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                console.log('API响应状态:', response.status);

                if (!response.ok) {
                    if (response.status === 401) {
                        console.log('认证失败，跳转到登录页');
                        window.location.href = '/admin/login.html';
                        return;
                    }
                    throw new Error('加载用户数据失败');
                }

                const result = await response.json();
                console.log('API返回数据:', result);

                if (result.code === 0) {
                    renderUserList(result.data.list);
                    setupPagination(result.data.count, page);
                } else {
                    throw new Error(result.message || '加载用户数据失败');
                }
            } catch (error) {
                console.error('加载用户列表失败:', error);
                document.getElementById('userList').innerHTML = 
                    '<tr><td colspan="12" class="text-center text-danger">加载失败: ' + error.message + '</td></tr>';
            }
        }

        // 渲染用户列表
        function renderUserList(users) {
            const tbody = document.getElementById('userList');
            if (!users || users.length === 0) {
                tbody.innerHTML = '<tr><td colspan="12" class="text-center">暂无用户数据</td></tr>';
                return;
            }

            tbody.innerHTML = users.map(user => {
                const bmi = calculateBMI(user.weight, user.height);
                const bmiStatus = getBMIStatus(bmi);
                
                return `
                    <tr>
                        <td>${user.id}</td>
                        <td>
                            <img src="${user.avatar || '/images/default-avatar.png'}" 
                                 alt="用户头像" 
                                 class="avatar-sm">
                        </td>
                        <td>${user.username}</td>
                        <td>${user.nickname || '-'}</td>
                        <td>${user.gender === 'male' ? '男' : '女'}</td>
                        <td>${user.height || '-'}</td>
                        <td>${user.weight || '-'}</td>
                        <td>${user.age || '-'}</td>
                        <td>
                            <span class="badge ${getBMIBadgeClass(bmi)}">
                                ${bmi} (${bmiStatus})
                            </span>
                        </td>
                        <td>${user.goal || '-'}</td>
                        <td>${new Date(user.createdAt).toLocaleString()}</td>
                        <td>
                            <button class="btn btn-danger btn-sm" onclick="showDeleteModal(${user.id})">
                                删除
                            </button>
                        </td>
                    </tr>
                `;
            }).join('');
        }

        // 设置分页
        function setupPagination(total, currentPage) {
            const totalPages = Math.ceil(total / 10);
            const pagination = document.getElementById('pagination');
            
            let paginationHtml = `
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadUsers(${currentPage - 1}); return false;">上一页</a>
                </li>
            `;

            for (let i = 1; i <= totalPages; i++) {
                paginationHtml += `
                    <li class="page-item ${i === currentPage ? 'active' : ''}">
                        <a class="page-link" href="#" onclick="loadUsers(${i}); return false;">${i}</a>
                    </li>
                `;
            }

            paginationHtml += `
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadUsers(${currentPage + 1}); return false;">下一页</a>
                </li>
            `;

            pagination.innerHTML = paginationHtml;
        }

        // 显示删除确认框
        function showDeleteModal(userId) {
            deleteUserId = userId;
            deleteModal.show();
        }

        // 确认删除用户
        async function confirmDelete() {
            if (!deleteUserId) return;

            try {
                const token = localStorage.getItem('adminToken');
                if (!token) {
                    window.location.href = '/admin/login.html';
                    return;
                }

                const response = await fetch(`/api/admin/users/${deleteUserId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (!response.ok) {
                    if (response.status === 401) {
                        window.location.href = '/admin/login.html';
                        return;
                    }
                    throw new Error('删除用户失败');
                }

                const result = await response.json();
                if (result.code === 0) {
                    deleteModal.hide();
                    loadUsers(currentPage);
                } else {
                    throw new Error(result.message || '删除用户失败');
                }
            } catch (error) {
                alert(error.message);
            }
        }

        // 搜索用户
        function searchUsers() {
            const searchInput = document.getElementById('searchInput');
            currentPage = 1;
            loadUsers(1, searchInput.value);
        }

        // 监听搜索框回车事件
        document.getElementById('searchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchUsers();
            }
        });
    </script>
</body>
</html>